#coding=utf-8
from uliweb import expose,json

#可以省略直接引用
from uliweb import request, error, redirect

from models import encrypt_password,check_password

"""
用户信息维护
"""
def __begin__():
    """
    用户验证 权限验证
    """
    from uliweb import functions
    functions.require_login()
    return functions.has_role()

@expose('/user')
class User(object):

    def __init__(self):
        from uliweb.orm import get_model
        self.usermodel = get_model('user')


    def _get_user(self, id):
        user = self.usermodel.get(int(id))
        if not user:
            error('没找到这条记录')
        return user
    
    def user(self):
        return {}

    
    def useradd(self):
        return {}
    
    def userdel(self):
        """
        删除用户
        """
        user_id = request.POST.get('id')
        
        mid = []
        for i in user_id.split(','):
            mid.append(int(i))
            
        #一次删除多个
        self.usermodel.filter(self.usermodel.c.id.in_(mid)).remove()
        
        d = {"status":"200","msg":"锁定用户成功"}
        return json(d)
    
    def useredit(self):
        """
        编辑用户
        """
        
        _id = request.GET.get("id")

        userinfo = list(self.usermodel.filter(self.usermodel.c.id == int(_id)).limit(1))[0]
    
        if userinfo.is_superuser:
            is_superuser = 1
        else:
            is_superuser = 0


        return {'is_superuser':is_superuser}
    
    def usersave(self):
        """
        保存修改用户
        """
        
        user_id = request.POST.get('id')
        
        username = request.POST.get('user_name')
        password = request.POST.get('user_passwd')
        nickname = request.POST.get('user_real_name')
        mobile = request.POST.get('user_phone')
        email = request.POST.get('user_email')
        is_superuser = request.POST.get('is_superuser')

        if request.user.is_superuser:
            is_superuser = int(is_superuser)
        else:
            is_superuser = 0
            
        if user_id == None:
            user = self.usermodel(username=username,
                      nickname=nickname,
                      mobile=mobile,
                      email=email,
                      #密码使用sha1加密
                      password=encrypt_password(password),
                      is_superuser = is_superuser,
                      deleted=1
                      )
        else:
            user = self._get_user(user_id)
            user.username = username
            user.nickname=nickname
            user.mobile=mobile
            user.email=email
            user.is_superuser=is_superuser
        
        try:
            user.save()
            
            return json({"success":200,"msg":"保存成功"})
        except:
            return json({"error":500,"msg":"用户已经存在"})
    
    
    def userpass(self):
        """
        修改用户密码
        """
        _id = request.GET.get("id")
        
        return {}
    
    def userpasssave(self):
        """
        保存密码修改
        """
        user_id = request.POST.get('id')
        
        user = self._get_user(user_id)
            
        password = request.POST.get('user_passwd').strip()

        user.password = encrypt_password(password)
        
        user.save()
            
        return json({"success":200,"msg":"密码修改成功"})
        
    def userunlocklogin(self):
        """
        恢复用户登录状态
        """
        user_id = request.POST.get('id')
        
        mid = []
        for i in user_id.split(','):
            mid.append(int(i))
        
        #将删除标志值为0 防止关联数据
        self.usermodel.filter(self.usermodel.c.id.in_(mid)).update(deleted=1)
        
        d = {"status":"200","msg":"恢复登录成功"}
        return json(d)    

    def userlocklogin(self):
        """
        锁定用户登录状态
        """
        user_id = request.POST.get('id')
        
        mid = []
        for i in user_id.split(','):
            mid.append(int(i))
        
        #将删除标志值为0 防止关联数据
        self.usermodel.filter(self.usermodel.c.id.in_(mid)).update(deleted=0)
        
        d = {"status":"200","msg":"恢复登录成功"}
        return json(d)   
    
    
@expose('/users/search')
def users_search():
    """
    用于权限搜索
    """
    from uliweb.orm import get_model
    
    User = get_model('user')
    v_field = request.values.get('label', 'title')
    if request.values.get('term'):
        result = []
        name = request.values.get('term')
        for x in User.filter(User.c.username.like('%'+name+'%') | User.c.nickname.like('%'+name+'%')).limit(functions.get_var('USER_ADMIN/SEARCH_USERS_LIMIT')):
            if x.nickname:
                title = x.nickname+'('+x.username+')'
            else:
                title = x.username
            result.append({'id':x.id, v_field:title})
        return json(result)
    else:
        return json([])